import os

from flask import Flask, request, jsonify
from flask.cli import load_dotenv
from flask_oauthlib.provider import OAuth2Provider
from datetime import datetime, timedelta
import hashlib

from db.models import OAuthClient

app = Flask(__name__)
load_dotenv()  # 读取 .env 文件
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['OAUTH2_PROVIDER_TOKEN_EXPIRES_IN'] = 7200  # Token 2小时过期

oauth = OAuth2Provider(app)

# 存储 access_token
tokens = {}


# 获取客户端信息
def get_client(client_id):
    o_client = OAuthClient.query.filter_by(client_id=client_id).first()
    if o_client:
        return ''
    return o_client.secret_key


# 认证 `client_id` 和 `secret_key`
def verify_client(client_id, secret_key):
    client = get_client(client_id)
    if client == '':
        return False
    if client and client["secret_key"] == hashlib.sha256(secret_key.encode()).hexdigest():
        return True
    return False


@app.route('/oauth/token', methods=['POST'])
def access_token():
    client_id = request.form.get('client_id')
    secret_key = request.form.get('secret_key')

    if verify_client(client_id, secret_key):
        _access_token = f"token_{datetime.utcnow().timestamp()}"
        tokens[_access_token] = {
            "client_id": client_id,
            "expires_at": datetime.utcnow() + timedelta(seconds=3600)
        }
        return jsonify({
            "access_token": _access_token,
            "token_type": "bearer",
            "expires_in": 3600
        })

    return jsonify({"error": "invalid_client"}), 401


@app.route('/api/resource', methods=['GET'])
def protected_resource():
    auth_header = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({"error": "invalid_token"}), 401

    _access_token = auth_header.split(" ")[1]
    token_data = tokens.get(_access_token)

    if not token_data or token_data["expires_at"] < datetime.utcnow():
        return jsonify({"error": "token_expired"}), 401

    return jsonify({"message": "This is a protected resource"})
